<template>
  <el-card>
    <!-- 显示当前病房信息 -->
    <div v-if="currentWardInfo" class="current-ward-info">
      <el-tag type="primary">当前病房：{{ currentWardInfo.wardNo }} - {{ currentWardInfo.roomName }}</el-tag>
    </div>

    <!-- 操作按钮区域 -->
    <div class="operation-bar">
      <el-button type="success" @click="handleAdd">新增病床</el-button>
      <el-button @click="handleBack">返回</el-button>
    </div>

    <!-- 表格 -->
    <el-table :data="tableData" border stripe style="width: 100%; margin:12px 0">
      <el-table-column prop="id" label="ID" width="60" />
      <el-table-column prop="wardNo" label="所属病房" />
      <el-table-column prop="bedNo" label="病床编号" />
      <el-table-column prop="roomName" label="所属科室" />
      <el-table-column prop="status" label="状态" width="80">
        <template #default="{row}">
          <el-tag :type="row.status === 0 ? 'success' : 'danger'">
            {{ row.status === 0 ? '空闲' : '占用' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="220">
        <template #default="{row}">
          <el-button size="small" @click="handleEdit(row)">编辑</el-button>
          <el-button size="small" type="danger" @click="handleDel(row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <el-pagination
        background
        layout="total, sizes, prev, pager, next, jumper"
        :total="pagination.total"
        :page-size="pagination.pageSize"
        :current-page="pagination.pageNum"
        :page-sizes="[5,10,20,50]"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
    />
  </el-card>

  <!-- 新增/编辑弹窗 -->
  <el-dialog v-model="dialogVisible" :title="dialogTitle" width="480px">
    <el-form ref="formRef" :model="form" label-width="100px" :rules="formRules">
      <el-form-item label="病床编号" prop="bedNo">
        <el-input v-model="form.bedNo" placeholder="请输入病床编号" />
      </el-form-item>
      <el-form-item label="所属病房" prop="wardId">
        <el-select v-model="form.wardId" placeholder="请选择病房" style="width:100%" disabled>
          <el-option :label="currentWardInfo ? currentWardInfo.wardNo : ''" :value="wardId" />
        </el-select>
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-radio-group v-model="form.status">
          <el-radio :label="0">空闲</el-radio>
          <el-radio :label="1">占用</el-radio>
        </el-radio-group>
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="dialogVisible=false">取消</el-button>
      <el-button type="primary" @click="submitForm">确定</el-button>
    </template>
  </el-dialog>
</template>

<script>
import {ElMessage, ElMessageBox} from 'element-plus'
import {findWardId, addBed, updateBed, delBed} from '../api/bed.js'
import {findWard} from '../api/ward.js'

export default {
  name: 'BedView',
  data() {
    return {
      wardId: null,
      currentWardInfo: null,
      pagination: {
        pageNum: 1,
        pageSize: 10,
        total: 0
      },
      tableData: [],
      dialogVisible: false,
      dialogTitle: '',
      isAdd: true,
      form: {
        bedNo: '',
        wardId: '',
        status: 0
      },
      // 新增WebSocket相关
      websocket: null,
      // 记录最近的操作ID，避免重复处理自己的操作
      lastOperationId: null,
      websocketConnected: false,
      reconnectCount: 0,
      maxReconnectCount: 3,
      // 新增：消息去重相关
      processedMessages: new Set(),
      lastMessageTime: 0,
      messageDebounceTime: 500
    }
  },
  computed: {
    formRules() {
      return {
        bedNo: [
          {required: true, message: '请输入病床编号', trigger: 'blur'}
        ],
        wardId: [
          {required: true, message: '请选择所属病房', trigger: 'change'}
        ],
        status: [
          {required: true, message: '请选择状态', trigger: 'change'}
        ]
      }
    }
  },
  mounted() {
    this.wardId = this.$route.query.wardId
    // console.log('病房ID:', this.wardId)
    if (!this.wardId) {
      ElMessage.error('未获取到病房信息')
      return
    }
    this.loadData()
    this.loadWardInfo()
    // 新增：初始化WebSocket连接
    this.initWebSocket()
  },
  beforeUnmount() {
    // 新增：组件销毁时关闭WebSocket
    if (this.websocket) {
      this.websocket.close()
    }
  },
  methods: {
    async loadData() {
      if (!this.wardId) return

      const {pageNum, pageSize} = this.pagination
      const params = {
        wardId: this.wardId,
        pageNum,
        pageSize
      }

      try {
        // console.log('调用API参数:', params)
        const {data: res} = await findWardId(params)
        // console.log('API响应:', res)
        if (res.code === 200) {
          this.tableData = res.obj.list || []
          this.pagination.total = res.obj.total
          // console.log('加载到的病床数据:', this.tableData)
        } else {
          ElMessage.error(res.msg || '加载失败')
        }
      } catch (error) {
        console.error('API调用错误:', error)
        ElMessage.error('加载数据失败')
      }
    },

    async loadWardInfo() {
      try {
        const {data: res} = await findWard({pageNum: 1, pageSize: 1000})
        if (res.code === 200) {
          const wardList = res.obj.list || []
          this.currentWardInfo = wardList.find(ward => ward.id == this.wardId)
          if (this.currentWardInfo) {
            this.form.wardId = this.wardId
          }
        }
      } catch (error) {
        ElMessage.error('加载病房信息失败')
      }
    },

    handleSizeChange(val) {
      this.pagination.pageSize = val
      this.loadData()
    },

    handleCurrentChange(val) {
      this.pagination.pageNum = val
      this.loadData()
    },

    handleAdd() {
      this.isAdd = true
      this.dialogTitle = '新增病床'
      this.form = {
        bedNo: '',
        wardId: this.wardId,
        status: 0
      }
      this.dialogVisible = true
    },

    handleEdit(row) {
      this.isAdd = false
      this.dialogTitle = '编辑病床'
      this.form = {
        id: row.id,
        bedNo: row.bedNo,
        wardId: this.wardId,
        status: row.status
      }
      this.dialogVisible = true
    },

    handleBack() {
      this.$router.go(-1)
    },

    handleDel(row) {
      ElMessageBox.confirm(
          `确认删除病床【${row.bedNo}】？`,
          '提示',
          {type: 'warning'}
      )
          .then(async () => {
            // 记录操作ID
            this.lastOperationId = `del_${row.id}_${Date.now()}`
            const {data: res} = await delBed(row.id)
            if (res.code === 200) {
              ElMessage.success('删除成功')
              this.loadData() // 自己的操作正常刷新
            } else {
              ElMessage.error(res.msg || '删除失败')
            }
          })
          .catch(() => {
          })
    },

    async submitForm() {
      await this.$refs.formRef.validate()

      // 记录操作ID
      const timestamp = Date.now()
      if (this.isAdd) {
        this.lastOperationId = `add_${this.form.bedNo}_${timestamp}`
      } else {
        this.lastOperationId = `update_${this.form.id}_${timestamp}`
      }

      const api = this.isAdd ? addBed : updateBed
      const {data: res} = await api(this.form)

      if (res.code === 200) {
        ElMessage.success(this.isAdd ? '新增成功' : '修改成功')
        this.dialogVisible = false
        this.loadData() // 自己的操作正常刷新
      } else {
        ElMessage.error(res.msg || '操作失败')
      }
    },

    initWebSocket() {
      if (!this.wardId) return

      try {

        const currentHost = window.location.hostname;
        const wsUrl = `ws://${currentHost}:8080/ws/ward/${this.wardId}`;


        this.websocket = new WebSocket(wsUrl);

        this.websocket.onopen = () => {
          // console.log('WebSocket连接成功！');
          this.websocketConnected = true;
          this.reconnectCount = 0; // 重置重连计数
          // ElMessage.success('实时连接已建立');
        };

        this.websocket.onmessage = (event) => {
          try {
            const message = JSON.parse(event.data);
            // console.log('收到实时消息:', message);
            this.handleRealTimeMessage(message);
          } catch (error) {
            console.error('解析消息失败:', error);
          }
        };

        this.websocket.onclose = (event) => {
          console.log('WebSocket连接关闭:', event.code, event.reason);
          this.websocketConnected = false;

          // 自动重连逻辑
          if (this.reconnectCount < this.maxReconnectCount) {
            this.reconnectCount++;
            console.log(`尝试第${this.reconnectCount}次重连...`);
            setTimeout(() => {
              this.initWebSocket();
            }, 2000);
          } else {
            ElMessage.warning('实时连接失败，请手动刷新页面查看最新数据');
          }
        };

        this.websocket.onerror = (error) => {
          console.error('WebSocket连接错误:', error);
          this.websocketConnected = false;
        };

      } catch (error) {
        console.error('初始化WebSocket失败:', error);
        ElMessage.error('WebSocket初始化失败');
      }
    },

    handleRealTimeMessage(message) {
      const { type, bedNo, bedId, status, operationId } = message

      // 防抖处理：避免短时间内重复处理相同消息
      const now = Date.now()
      if (now - this.lastMessageTime < this.messageDebounceTime) {
        return
      }
      this.lastMessageTime = now

      const messageKey = `${type}_${bedId}_${now}`
      if (this.processedMessages.has(messageKey)) {
        return
      }
      this.processedMessages.add(messageKey)

      // 清理过期的消息记录
      if (this.processedMessages.size > 100) {
        const firstKey = this.processedMessages.values().next().value
        this.processedMessages.delete(firstKey)
      }


      if (this.lastOperationId && operationId && this.lastOperationId === operationId) {
        this.lastOperationId = null // 重置
        return
      }

      // 移除所有ElMessage.info提示，只保留数据刷新
      switch (type) {
        case 'bedAdd':
        case 'bedDel':
        case 'bedStatus':
        case 'bedUpdate':
          this.loadData()
          break
      }
    }
  }
}
</script>

<style scoped>
.operation-bar {
  margin-bottom: 12px;
}

.current-ward-info {
  margin-bottom: 16px;
  padding: 8px 0;
}
</style>













<!--<template>-->
<!--  <el-card>-->
<!--    &lt;!&ndash; 显示当前病房信息 &ndash;&gt;-->
<!--    <div v-if="currentWardInfo" class="current-ward-info">-->
<!--      <el-tag type="primary">当前病房：{{ currentWardInfo.wardNo }} - {{ currentWardInfo.roomName }}</el-tag>-->
<!--    </div>-->

<!--    &lt;!&ndash; 操作按钮区域 &ndash;&gt;-->
<!--    <div class="operation-bar">-->
<!--      <el-button type="success" @click="handleAdd">新增病床</el-button>-->
<!--      <el-button @click="handleBack">返回</el-button>-->
<!--    </div>-->

<!--    &lt;!&ndash; 表格 &ndash;&gt;-->
<!--    <el-table :data="tableData" border stripe style="width: 100%; margin:12px 0">-->
<!--      <el-table-column prop="id" label="ID" width="60" />-->
<!--      <el-table-column prop="wardNo" label="所属病房" />-->
<!--      <el-table-column prop="bedNo" label="病床编号" />-->
<!--      <el-table-column prop="roomName" label="所属科室" />-->
<!--      <el-table-column prop="status" label="状态" width="80">-->
<!--        <template #default="{row}">-->
<!--          <el-tag :type="row.status === 0 ? 'success' : 'danger'">-->
<!--            {{ row.status === 0 ? '空闲' : '占用' }}-->
<!--          </el-tag>-->
<!--        </template>-->
<!--      </el-table-column>-->
<!--      <el-table-column label="操作" width="220">-->
<!--        <template #default="{row}">-->
<!--          <el-button size="small" @click="handleEdit(row)">编辑</el-button>-->
<!--          <el-button size="small" type="danger" @click="handleDel(row)">删除</el-button>-->
<!--        </template>-->
<!--      </el-table-column>-->
<!--    </el-table>-->

<!--    &lt;!&ndash; 分页 &ndash;&gt;-->
<!--    <el-pagination-->
<!--        background-->
<!--        layout="total, sizes, prev, pager, next, jumper"-->
<!--        :total="pagination.total"-->
<!--        :page-size="pagination.pageSize"-->
<!--        :current-page="pagination.pageNum"-->
<!--        :page-sizes="[5,10,20,50]"-->
<!--        @size-change="handleSizeChange"-->
<!--        @current-change="handleCurrentChange"-->
<!--    />-->
<!--  </el-card>-->

<!--  &lt;!&ndash; 新增/编辑弹窗 &ndash;&gt;-->
<!--  <el-dialog v-model="dialogVisible" :title="dialogTitle" width="480px">-->
<!--    <el-form ref="formRef" :model="form" label-width="100px" :rules="formRules">-->
<!--      <el-form-item label="病床编号" prop="bedNo">-->
<!--        <el-input v-model="form.bedNo" placeholder="请输入病床编号" />-->
<!--      </el-form-item>-->
<!--      <el-form-item label="所属病房" prop="wardId">-->
<!--        <el-select v-model="form.wardId" placeholder="请选择病房" style="width:100%" disabled>-->
<!--          <el-option :label="currentWardInfo ? currentWardInfo.wardNo : ''" :value="wardId" />-->
<!--        </el-select>-->
<!--      </el-form-item>-->
<!--      <el-form-item label="状态" prop="status">-->
<!--        <el-radio-group v-model="form.status">-->
<!--          <el-radio :label="0">空闲</el-radio>-->
<!--          <el-radio :label="1">占用</el-radio>-->
<!--        </el-radio-group>-->
<!--      </el-form-item>-->
<!--    </el-form>-->
<!--    <template #footer>-->
<!--      <el-button @click="dialogVisible=false">取消</el-button>-->
<!--      <el-button type="primary" @click="submitForm">确定</el-button>-->
<!--    </template>-->
<!--  </el-dialog>-->
<!--</template>-->

<!--<script>-->
<!--import {ElMessage, ElMessageBox} from 'element-plus'-->
<!--import {findWardId, addBed, updateBed, delBed} from '../api/bed.js'-->
<!--import {findWard} from '../api/ward.js'-->

<!--export default {-->
<!--  name: 'BedView',-->
<!--  data() {-->
<!--    return {-->
<!--      wardId: null,-->
<!--      currentWardInfo: null,-->
<!--      pagination: {-->
<!--        pageNum: 1,-->
<!--        pageSize: 10,-->
<!--        total: 0-->
<!--      },-->
<!--      tableData: [],-->
<!--      dialogVisible: false,-->
<!--      dialogTitle: '',-->
<!--      isAdd: true,-->
<!--      form: {-->
<!--        bedNo: '',-->
<!--        wardId: '',-->
<!--        status: 0-->
<!--      }-->
<!--    }-->
<!--  },-->
<!--  computed: {-->
<!--    formRules() {-->
<!--      return {-->
<!--        bedNo: [-->
<!--          {required: true, message: '请输入病床编号', trigger: 'blur'}-->
<!--        ],-->
<!--        wardId: [-->
<!--          {required: true, message: '请选择所属病房', trigger: 'change'}-->
<!--        ],-->
<!--        status: [-->
<!--          {required: true, message: '请选择状态', trigger: 'change'}-->
<!--        ]-->
<!--      }-->
<!--    }-->
<!--  },-->
<!--  mounted() {-->
<!--    this.wardId = this.$route.query.wardId-->
<!--    console.log('病房ID:', this.wardId)-->
<!--    if (!this.wardId) {-->
<!--      ElMessage.error('未获取到病房信息')-->
<!--      return-->
<!--    }-->
<!--    this.loadData()-->
<!--    this.loadWardInfo()-->
<!--  },-->
<!--  methods: {-->
<!--    async loadData() {-->
<!--      if (!this.wardId) return-->

<!--      const {pageNum, pageSize} = this.pagination-->
<!--      const params = {-->
<!--        wardId: this.wardId,-->
<!--        pageNum,-->
<!--        pageSize-->
<!--      }-->

<!--      try {-->
<!--        console.log('调用API参数:', params)-->
<!--        const {data: res} = await findWardId(params)-->
<!--        console.log('API响应:', res)-->
<!--        if (res.code === 200) {-->
<!--          this.tableData = res.obj.list || []-->
<!--          this.pagination.total = res.obj.total-->
<!--          console.log('加载到的病床数据:', this.tableData)-->
<!--        } else {-->
<!--          ElMessage.error(res.msg || '加载失败')-->
<!--        }-->
<!--      } catch (error) {-->
<!--        console.error('API调用错误:', error)-->
<!--        ElMessage.error('加载数据失败')-->
<!--      }-->
<!--    },-->

<!--    async loadWardInfo() {-->
<!--      try {-->
<!--        const {data: res} = await findWard({pageNum: 1, pageSize: 1000})-->
<!--        if (res.code === 200) {-->
<!--          const wardList = res.obj.list || []-->
<!--          this.currentWardInfo = wardList.find(ward => ward.id == this.wardId)-->
<!--          if (this.currentWardInfo) {-->
<!--            this.form.wardId = this.wardId-->
<!--          }-->
<!--        }-->
<!--      } catch (error) {-->
<!--        ElMessage.error('加载病房信息失败')-->
<!--      }-->
<!--    },-->

<!--    handleSizeChange(val) {-->
<!--      this.pagination.pageSize = val-->
<!--      this.loadData()-->
<!--    },-->

<!--    handleCurrentChange(val) {-->
<!--      this.pagination.pageNum = val-->
<!--      this.loadData()-->
<!--    },-->

<!--    handleAdd() {-->
<!--      this.isAdd = true-->
<!--      this.dialogTitle = '新增病床'-->
<!--      this.form = {-->
<!--        bedNo: '',-->
<!--        wardId: this.wardId,-->
<!--        status: 0-->
<!--      }-->
<!--      this.dialogVisible = true-->
<!--    },-->

<!--    handleEdit(row) {-->
<!--      this.isAdd = false-->
<!--      this.dialogTitle = '编辑病床'-->
<!--      this.form = {-->
<!--        id: row.id,-->
<!--        bedNo: row.bedNo,-->
<!--        wardId: this.wardId,-->
<!--        status: row.status-->
<!--      }-->
<!--      this.dialogVisible = true-->
<!--    },-->

<!--    handleBack() {-->
<!--      this.$router.go(-1)-->
<!--    },-->

<!--    handleDel(row) {-->
<!--      ElMessageBox.confirm(-->
<!--          `确认删除病床【${row.bedNo}】？`,-->
<!--          '提示',-->
<!--          {type: 'warning'}-->
<!--      )-->
<!--          .then(async () => {-->
<!--            const {data: res} = await delBed(row.id)-->
<!--            if (res.code === 200) {-->
<!--              ElMessage.success('删除成功')-->
<!--              this.loadData()-->
<!--            } else {-->
<!--              ElMessage.error(res.msg || '删除失败')-->
<!--            }-->
<!--          })-->
<!--          .catch(() => {-->
<!--          })-->
<!--    },-->

<!--    async submitForm() {-->
<!--      await this.$refs.formRef.validate()-->

<!--      const api = this.isAdd ? addBed : updateBed-->
<!--      const {data: res} = await api(this.form)-->

<!--      if (res.code === 200) {-->
<!--        ElMessage.success(this.isAdd ? '新增成功' : '修改成功')-->
<!--        this.dialogVisible = false-->
<!--        this.loadData()-->
<!--      } else {-->
<!--        ElMessage.error(res.msg || '操作失败')-->
<!--      }-->
<!--    }-->
<!--  }-->
<!--}-->
<!--</script>-->

<!--<style scoped>-->
<!--.operation-bar {-->
<!--  margin-bottom: 12px;-->
<!--}-->

<!--.current-ward-info {-->
<!--  margin-bottom: 16px;-->
<!--  padding: 8px 0;-->
<!--}-->
<!--</style>-->